package com.pv.pulse;

import java.util.concurrent.TimeUnit;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.ProxyConfig;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class MyThread implements Runnable {
	
	public void run() {
		try {
//			String webUrl="http://sx.xuanzhen-tech.com/test.html";
//			String webUrl = "http://club.lenovo.com.cn/forum-1172-1.html?pmf_group=waibushichangyinliuxiaoguojianko&pmf_medium=market_type_free_search&pmf_source=W000008C001316R981";  
			while(true){
				getHtmlPage();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private void getHtmlPage() throws Exception{
        final WebClient webClient=new WebClient(BrowserVersion.FIREFOX_24);
        ProxyConnection conn=ProxyPool.getProxy();
        ProxyConfig proxyConfig = conn.getProxyConfig();
        webClient.getOptions().setProxyConfig(proxyConfig);
        webClient.getOptions().setJavaScriptEnabled(true);
        webClient.getOptions().setCssEnabled(false);
        webClient.getOptions().setActiveXNative(false);
        
        System.out.println("查询中，请稍候");
        System.out.println(proxyConfig.getProxyHost()+":"+proxyConfig.getProxyPort());
		try {
			for(String requestUrl : ProxyPool.request_urls){
				System.out.println("请求url:"+requestUrl);
				HtmlPage page = webClient.getPage(requestUrl);
				TimeUnit.SECONDS.sleep(ProxyPool.request_first_interval);  //web请求数据需要时间，必须让主线程休眠片刻  
				page.refresh();
				TimeUnit.SECONDS.sleep(ProxyPool.request_refresh_interval);  //web请求数据需要时间，必须让主线程休眠片刻  
			}
			System.out.println("查询数据成功");
			boolean isContinue=ProxyPool.requestIndexPlus();
	        if(!isContinue){
	        	System.out.println("请求数已经达到 停止线程 stop "+Thread.currentThread().getName());
	        	Thread.currentThread().stop();
	        	System.exit(0);
	        }
			
		} catch (Exception e) {
//			conn.ErrorCountPlus();
//			conn.close();
//			System.out.println("出现异常，停止线程 stop "+Thread.currentThread().getName());
//			Thread.currentThread().stop();
			// TODO Auto-generated catch block
			boolean isSkip=ProxyPool.skipThread();
	        if(isSkip){
	        	System.out.println("请求数已经达到并且出现异常 停止线程 stop "+Thread.currentThread().getName());
	        	Thread.currentThread().stop();
	        	System.exit(0);
	        }
			System.out.println("查询数据失败");
			e.printStackTrace();
			conn.ErrorCountPlus();
//			TimeUnit.SECONDS.sleep(20);	//连接失败就停留时间长一点，减少消耗
		}finally{
			conn.close();
			webClient.closeAllWindows();
		}
        
    }
}